﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NHLTester.Classes
{
    public class Symulation
    {
        private SymulationSettings Settings = new SymulationSettings();
        private List<GameStat> Stats { get; set; }
        private SymulationResult Result { get; set; }

        private double Account { get; set; }
        private double WinValue = 0;
        private double BetTillNow = 0;
        private double BaseValueToBet ;
        private double ValueToBet = 0;
        private int Attempt = 1;
        private bool AmIWinner = true;
        private bool AreWeInGame = false;

        public Symulation(SymulationSettings settings, List<GameStat> stats, string fileName)
        {
            this.Settings = settings;
            this.Stats = stats;
            Result = new SymulationResult();
            Result.StartAccount = Settings.Account;
            Result.FileName = fileName;
        }

        private void SymulationReset()
        {
            Account = Settings.Account;
            Result.MinimalAccount = Account;
        }

        public SymulationResult Start()
        {
            SymulationReset();

            foreach (var item in Stats)
            {
                if (Attempt == 1)
                    BaseValueToBet = SetNewValueToBet();

                ValueToBet = (BetTillNow / (Settings.WinRatio - 1)) + BaseValueToBet;

                BetTillNow += ValueToBet;
                WinValue = ValueToBet * Settings.WinRatio;
                Account -= ValueToBet;

                if (Account < Result.MinimalAccount)
                    Result.MinimalAccount = Account;

                if (Settings.Account <= 0)
                    break;



                if (item.GF + item.GA < Settings.Border)
                {
                    BetTillNow = 0;
                    AmIWinner = true;
                    Attempt = 1;
                    Account += WinValue;
                    BaseValueToBet = SetNewValueToBet();
                }
                else
                {
                    AmIWinner = false;
                    Attempt++;
                    if (Attempt == Settings.NumberOfGamesToBreak + 1)
                    {
                        Result.NumberOfBreaks++;
                        Attempt = 1;
                        BetTillNow = 0;
                        BaseValueToBet = SetNewValueToBet();
                    }
                }
            }
            Result.FinalAccount = Account;
            
            return Result;
        }

        private double SetNewValueToBet()
        {
            return Settings.SingleBetPercentage * Account;
        }
    }
}
